const jwt = require('jsonwebtoken');
const {secret} = require('../config');
const User = require('../models/user');
const { createIndexes } = require('../models/user');
const { use } = require('../routers/user');
class UserCtl{
    /**
     * 
     * @param {*} ctx 
     * 用户登录接口
     */
    async login(ctx){
            // ctx.body = await User.find();
            console.log(ctx.request.body);
            //校验请求体的用户名和密码;
            ctx.verifyParams({
                account : {type: 'string', required :true},
                password : {type : 'string',required : true}
            });
            const user = await User.findOne(ctx.request.body);
            if(!user){
                ctx.throw(401,'用户名或密码错误!');
            }
            const {_id,nickName,headline,description,address,gender,avatarUrl} = user;
            //验证成功,生成token;
            //使用jwt签名,存放用户信息(非敏感信息),并设置过期时间;
            const token = jwt.sign({_id},secret,{expiresIn:'1d'});
            //将token返回给客户端;
            ctx.body = {user,token};
        
    }

    
    async find(ctx){
        ctx.body = await User.find();
    }

    /**
     * 
     * @param {*} ctx 
     * 用户信息接口,返回用户信息,可根据fields参数返回指定的数据域;
     */
    async findById(ctx){
        const {fields} = ctx.query;
        const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('');
        
        const user = await User.findById(ctx.params.id).select(selectFields);

        
        if(!user){
            ctx.throw(404,'用户不存在');
        }
        ctx.body = user;
    }
    /**
     * 
     * @param {*} ctx 
     * 创建用户;
     */
    async create(ctx){
        //检查用户是否已注册;
        let user  = ctx.request.body;
        //验证用户上传数据
        ctx.verifyParams({
            account : {
                type : 'string',required : true
            },
            password : {
                type : 'string',required : true
            }
        }); 
        const {account} = ctx.request.body;
        const repeaterUser = await User.findOne({account});
        if(repeaterUser){
            ctx.throw(409,'用户已经被注册了');
        }
        user = await new User(ctx.request.body).save();
        ctx.body = user; 
    }
    /**
     * 
     * @param {*} ctx 
     * 检测邮箱是否已被注册;
     * 
     */
    async isEmailExisted(ctx){
        const email = ctx.params.email;
        const user = await User.findOne({'email':email});
        if(user){
            ctx.throw(409,'邮箱已被占用,请使用其他邮箱注册');
        }
        ctx.status = 200;
    }


    async deleteById(ctx){
        const user = await User.findByIdAndRemove(ctx.params.id);
        if(!user){
            ctx.throw(404,'没有找到该用户!');
        }
        ctx.status = 204;
    }
    /**
     * 
     * @param {*} ctx 
     * 更新用户;
     */
    async updateById(ctx){
        //数据验证;
        ctx.verifyParams({
            nickName : {type: 'string', required: false},
            password : {type: 'string', required: false},
            avarar_url: {type: 'string', required: false},
            gender: {type:'string', required: false},
            headline: {type:'string', required: false},
            address: {type:'string', required: false},
            description: {type:'string', required: false}
        })
        const user = await User.findByIdAndUpdate(ctx.params.id,ctx.request.body,{new : true});
        
        if(!user){
            ctx.throw(404,'没有找到该用户!');
        }
        ctx.body = user;
    }
}
module.exports = new UserCtl();
